<!--
 * @Author: Xujianchen
 * @Date: 2024-08-13 16:21:31
 * @LastEditors: xujianchen
 * @LastEditTime: 2024-08-27 16:17:18
 * @Description: 上传图片
-->
<template>
  <div class="upload-box">
    <el-upload
      v-model:file-list="_fileList"
      action="#"
      accept="image/gif, image/jpeg, image/png"
      list-type="picture-card"
      :class="['upload', isDisabled ? 'disabled' : '', drag ? 'no-border' : '']"
      :multiple="true"
      :disabled="isDisabled"
      :limit="limit"
      :http-request="handleUpload"
      :before-upload="beforeUpload"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
      :on-error="handleError"
      :drag="drag"
    >
      <div class="upload-empty">
        <slot name="empty">
          <icon
            :name="iconName"
            :type="iconType"
            :size="iconSize"
          />
          <p>{{ title }}</p>
        </slot>
      </div>
      <template #file="{ file }">
        <img
          :src="file.url"
          class="upload-image"
        />
        <div
          class="upload-handle"
          @click.stop
        >
          <div
            class="handle-icon"
            @click="handlePreview(file)"
          >
            <icon :name="previewIcon" />
            <span>{{ previewText }}</span>
          </div>
          <div
            v-if="!isDisabled"
            class="handle-icon"
            @click="handleRemove(file)"
          >
            <icon :name="deleteIcon" />
            <span>{{ deleteIcon }}</span>
          </div>
        </div>
      </template>
    </el-upload>
    <div class="el-upload__tip">
      <slot name="tip">
        <span>大小不超过{{ maxSize }}M</span>
      </slot>
    </div>
    <el-image
      v-show="imgViewVisible"
      :url-list="[previewUrl]"
      @close="imgViewVisible = false"
    />
  </div>
</template>

<script setup>
import { ElMessage, formContextKey, formItemContextKey } from 'element-plus'
import { uploadImage } from '@/apis/upload'
import { uploadImgProps } from './props'

const modelValue = defineModel({
  type: Array,
  default: () => [],
})
const props = defineProps(uploadImgProps)

const formContext = inject(formContextKey, void 0)
const formItemContext = inject(formItemContextKey, void 0)

const isDisabled = computed(() => props.disabled || formContext?.disabled)
const borderRadius = computed(() => {
  const p = props
  return p.round ? '50%' : p.borderRadius
})

const _fileList = ref([])
const previewUrl = ref('')
const imgViewVisible = ref(false)

watch(
  () => modelValue.value,
  (newVal) => _fileList.value = newVal,
)

// 上传前处理
function beforeUpload(file) {
  const p = props
  const imgSize = file.size / 1024 / 1024 < p.maxSize
  const imgType = p.accept.includes(file.type)
  if (!imgType) {
    return ElMessage.warning('请选择正确的图片格式')
  }
  if (!imgSize) {
    return ElMessage.warning(`图片大小不能超过${p.maxSize}MB`)
  }

  return imgSize && imgType
}

// 上传
async function handleUpload(options) {
  const formData = new FormData()
  const data = options.data || {}
  formData.append(options.filename, options.file)
  for (const key in data) {
    formData.append(key, data[key])
  }

  try {
    const api = props?.api || uploadImage
    const res = await api(formData)
    options.onSuccess(res)
  } catch (error) {
    options.onError(error)
  }
}

function handleSuccess(res, file) {
  if (!res) return

  file.url = res.url
  modelValue.value = _fileList.value
  formItemContext?.prop && formContext?.validateField([formItemContext.prop])
  ElMessage.success('上传成功')
}

function handleError(err, file) {
  console.log(err, file)
  ElMessage.error('上传失败')
}

function handleRemove(file) {
  const files = _fileList.value.filter((item) => item.url !== file.url || item.name !== file.name)
  _fileList.value = files
  modelValue.value = files
}

function handleExceed() {
  ElMessage.warning(`最多只能上传${props.limit}张图片`)
}

function handlePreview(file) {
  previewUrl.value = file.url
  imgViewVisible.value = true
}
</script>

<style scoped lang="scss">
.is-error {
  .upload {

    :deep(.el-upload--picture-card),
    :deep(.el-upload-dragger) {
      border: 1px dashed var(--el-color-danger) !important;

      &:hover {
        border-color: var(--el-color-primary) !important;
      }
    }
  }
}

:deep(.disabled) {

  .el-upload--picture-card,
  .el-upload-dragger {
    cursor: not-allowed;
    background: var(--el-disabled-bg-color) !important;
    border: 1px dashed var(--el-border-color-darker);

    &:hover {
      border-color: var(--el-border-color-darker) !important;
    }
  }
}

.upload-box {
  .no-border {
    :deep(.el-upload--picture-card) {
      border: none !important;
    }
  }

  :deep(.upload) {
    .el-upload-dragger {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      padding: 0;
      overflow: hidden;
      border: 1px dashed var(--el-border-color-darker);
      border-radius: v-bind(borderRadius);

      &:hover {
        border: 1px dashed var(--el-color-primary);
      }
    }

    .el-upload-dragger.is-dragover {
      background-color: var(--el-color-primary-light-9);
      border: 2px dashed var(--el-color-primary) !important;
    }

    .el-upload-list__item,
    .el-upload--picture-card {
      width: v-bind('props.width');
      height: v-bind('props.height');
      background-color: transparent;
      border-radius: v-bind('borderRadius');
    }

    .upload-image {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }

    .upload-handle {
      position: absolute;
      top: 0;
      right: 0;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      cursor: pointer;
      background-color: rgb(0 0 0 / 60%);
      opacity: 0;
      transition: var(--el-transition-duration-fast);

      .handle-icon {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 0 6%;
        color: aliceblue;

        .el-icon {
          margin-bottom: 15%;
          font-size: 140%;
        }

        span {
          font-size: 100%;
        }
      }
    }

    .el-upload-list__item {
      &:hover {
        .upload-handle {
          opacity: 1;
        }
      }
    }

    .upload-empty {
      display: flex;
      flex-direction: column;
      align-items: center;
      font-size: $font-size-small;
      line-height: 30px;
      color: var(--el-color-info);

      .el-icon {
        font-size: 28px;
        color: var(--el-text-color-secondary);
      }
    }
  }

  .el-upload__tip {
    line-height: 15px;
    // text-align: center;
  }
}
</style>
